//
//  Stack.c
//  Stack
//
//  Created by Xavier on 2023/10/16.
//

#include "Stack.h"
// 初始化栈
void StackInit(Stack* ps){
    ps->arr = (STDataType*)malloc(sizeof(STDataType)*4);
    if (ps->arr == NULL) {
        printf("malloc error!\n");
        exit(-1);
    }
    ps->top = 0;
    ps->capacity = 4;
}

// 入栈
void StackPush(Stack* ps, STDataType data) {
    if (ps->top == ps->capacity) {
        STDataType* tmp = (STDataType*)realloc(ps->arr, sizeof(STDataType)*ps->capacity*2);
        if (tmp == NULL) {
            printf("realloc error!\n");
            exit(-1);
        }
        ps->arr = tmp;
        ps->capacity *= 2;

    }
    ps->arr[ps->top]  = data;
    ++ps->top;
}

// 出栈
void StackPop(Stack* ps){
    --ps->top;
}

// 获取栈顶元素
STDataType StackTop(Stack* ps) {
    return ps->arr[ps->top-1];
}

// 获取栈中有效元素个数
int StackSize(Stack* ps){
    return ps->top;
}

// 检测栈是否为空，如果为空返回非零结果，如果不为空返回0
int StackEmpty(Stack* ps) {
    return ps->top == 0 ? 0 : ps->top;
}
// 销毁栈
void StackDestroy(Stack* ps) {
    free(ps->arr);
    ps->top = ps->capacity = 0;
}

//打印栈
void StackPrint(Stack* ps){
    for (int i = ps->top-1; i>=0; i--) {
        printf("|");
        printf("%d", ps->arr[i]);
        printf("|\n");

//        printf("%d\n", ps->arr[i]);
//        if (i != 0)
//            printf("↑\n");
    }
    printf("\n");
}

//进制转换 十进制转八进制
void StackConvertDecimalToOctal(Stack* ps, STDataType val){
    int count = 0;
    while (val != 0) {
        ++count;
        int num = val%8;
        StackPush(ps, num);
        val /= 8;
    }
    
    while (count) {
        --count;
        int num = StackTop(ps);
        printf("%d", num);
        StackPop(ps);
    }
    printf("\n");

}




